package zj.com.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.List;

import zj.com.activities.CaptureActivity;
import zj.com.activities.ChoiceJcxActivity;
import zj.com.activities.JcxDetailActivity;
import zj.com.activities.MipcaActivityCapture;
import zj.com.adapter.JcxAdapter;
import zj.com.app.ZjApplication;
import zj.com.db.DBUtil;
import zj.com.model.Dic;
import zj.com.model.DjcModel;
import zj.com.model.InspectContent;
import zj.com.model.InspectItem;
import zj.com.model.JcxDB;
import zj.com.model.JcxDetailDB;
import zj.com.model.PgScan;
import zj.com.net.NetManager;
import zj.com.net.OnResponseListener;
import zj.com.util.LogUtils;
import zj.com.zj.R;

/**
 * Created by xi on 16/6/4.
 * 检查项
 */
public class JcxFragment extends Fragment implements View.OnClickListener {


    public TextView xz_tv,scan_tv;
    public ListView listView;
    public List<InspectItem> list;
    public JcxAdapter adapter;
    public Intent intent;

    public RelativeLayout error_rl;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_jcx, container, false);
        initView(view);
        initData();
        return view;
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser){
            list = ZjApplication.inspectItems;
            if(list.size() > 0){
                adapter.setDataChange(list);
            }

        }

    }

    public void initView(View view){

        error_rl = (RelativeLayout) view.findViewById(R.id.error_rl);
        xz_tv = (TextView) view.findViewById(R.id.xz_tv);
        xz_tv.setOnClickListener(this);
        scan_tv = (TextView) view.findViewById(R.id.scan_tv);
        scan_tv.setOnClickListener(this);
        listView = (ListView) view.findViewById(R.id.listView);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                intent = new Intent(getActivity(), JcxDetailActivity.class);
                InspectItem item = list.get(position);
                intent.putExtra("position", position);
                startActivity(intent);
            }
        });
    }

    public void initData(){
        list = new ArrayList<InspectItem>();

        adapter = new JcxAdapter(list,getActivity());
        listView.setAdapter(adapter);


        if(ZjApplication.isUpdateJcd){
            try {

                if(ZjApplication.jcd == null) return;

                List<JcxDB> jcxList =  DBUtil.getInstance(getActivity()).getDBManager().selector(JcxDB.class).where("inspectionno","=",ZjApplication.jcd.getInspectionNo()).findAll();
                List<InspectItem> inspectList = new ArrayList<>();
                PgScan pg  =new PgScan();
                pg.setUnitName(ZjApplication.jcd.getUnitName());
                pg.setProjectName(ZjApplication.jcd.getProjectName());

                ZjApplication.pgScan =pg;
                if(jcxList != null){


                    for (JcxDB jcx:jcxList){

                        InspectItem item = new InspectItem();
                        item.setRiskName(jcx.getRiskName());
                        item.setTaskName(jcx.getTaskName());
                        item.setInspectItemName(jcx.getInspectItemName());
                        item.setEndDate(jcx.getEndDate());
                        item.setInspectItemID(jcx.getInspectItemID());
                        item.setInspectItemCode(jcx.getInspectItemCode());
                        item.setInspectType(jcx.getInspectType());
                        item.setRiskType(jcx.getRiskType());
                        item.setSpecialtyCode(jcx.getSpecialtyCode());
                        item.setZyName(jcx.getZyName());
                        item.setId(jcx.getId());
                        item.setInspectionNo(jcx.getInspectionNo());

                        List<JcxDetailDB> jcxDetails = DBUtil.getInstance(getActivity()).getDBManager().selector(JcxDetailDB.class).where("inspectitemcode","=",jcx.getInspectItemCode()).and("inspectionno","=",jcx.getInspectionNo()).findAll();
                        List<InspectContent> contents = new ArrayList<InspectContent>();
                        for (JcxDetailDB jcxDetail:jcxDetails){

                            InspectContent content = new InspectContent();
                            content.setDes(jcxDetail.getContent());
                            content.setInspectContentID(jcxDetail.getContentId());
                            content.setPoints(jcxDetail.getPoints());
                            content.setInspectContentName(jcxDetail.getInspectContentName());
                            content.setMaxPoints(jcxDetail.getMaxPoints());
                            content.setRiskType(jcxDetail.getRiskType());
                            content.setRiskTypeName(jcxDetail.getRiskTypeName());
                            content.setId(jcxDetail.getId());
                            Dic dic = new Dic();
                            dic.setName(jcxDetail.getRiskName());
                            dic.setValue(jcxDetail.getRiskLevel());
                            content.setDic(dic);
                            String imgs = jcxDetail.getImgs();
                            List<String> imgList = new ArrayList<>();
                            if(imgs != null){
                              String[] imgArray =  imgs.split(",");
                              for (String str:imgArray){
                                  imgList.add(str);
                              }
                            }

                            LogUtils.getInstance().error("imgList="+imgList.size());
                            content.setImgs(imgList);
                            contents.add(content);
                        }
                        item.setContents(contents);
                        inspectList.add(item);

                    }

                    ZjApplication.inspectItems = inspectList;
                }

            } catch (DbException e) {
                e.printStackTrace();
            }

        }

    }

    @Override
    public void onResume() {
        super.onResume();
        list = ZjApplication.inspectItems;
        if(list != null && list.size() > 0){
            listView.setVisibility(View.VISIBLE);
            error_rl.setVisibility(View.GONE);
        }else{
            listView.setVisibility(View.GONE);
            error_rl.setVisibility(View.VISIBLE);
        }
        adapter.setDataChange(list);
    }

    public final int RQUEST_SCAN= 0x2210;

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.xz_tv:
                intent = new Intent(getActivity(), ChoiceJcxActivity.class);
                startActivity(intent);
                break;
            case R.id.scan_tv:
                intent = new Intent(getActivity(), CaptureActivity.class);
                startActivityForResult(intent, RQUEST_SCAN);
                break;
        }
    }

    public String SpecialtyName;
    public String SpecialtyCode;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(resultCode == getActivity().RESULT_OK){


            switch (requestCode){
                case RQUEST_SCAN:

                    String result = data.getStringExtra("result");
                    LogUtils.getInstance().error(result);
                    if(result != null){

                        String[] s =   result.split("//");

                        if(s.length >=2){
                            result = s[1];
                        }
                    }
                    try{
                        JSONObject obj = new JSONObject(result);
                         SpecialtyName = obj.getString("SpecialtyName");
                         SpecialtyCode = obj.getString("SpecialtyCode");
                         int InspectItemID = obj.getInt("InspectItemID");
                         obtainItem(InspectItemID);


                    }catch(Exception e){

                        LogUtils.getInstance().error("item===="+e.toString());
                    }
                    break;
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void obtainItem(int itemid){

        NetManager.getInstance(getActivity()).GetInspectItemDetail(SpecialtyName,SpecialtyCode,itemid + "", new OnResponseListener<InspectItem>() {
            @Override
            public void onComplete(boolean isOK, InspectItem item, int errorCode, String errorMsg) {

                if(item == null){

                    Toast.makeText(getActivity(), "扫码失败", Toast.LENGTH_SHORT).show();
                    return;
                }
                boolean isExsit = false;
                if(ZjApplication.inspectItems.size() > 0) {
                    for (int i = 0; i < ZjApplication.inspectItems.size(); i++) {


                        InspectItem inspect = ZjApplication.inspectItems.get(i);
                        if (inspect.getInspectItemID() == item.getInspectItemID()) {
                            isExsit = true;
                        }

                    }


                }
                if (!isExsit) {
                    ZjApplication.inspectItems.add(item);
                }
                list = ZjApplication.inspectItems;
                listView.setVisibility(View.VISIBLE);
                error_rl.setVisibility(View.GONE);
                LogUtils.getInstance().error("==list==="+list.size());
                adapter.setDataChange(list);
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {

            }
        });
    }
}
